<template>
  <van-popup v-model:show="innerVisible" round position="bottom">
    <div class="bg-1D1D1F">
      <div
        class="h-49 relative text-CCCCCC font-bold text-17 text-center flex justify-center items-center border-b border-solid border-3D3D3D"
      >
        <div>配音</div>
        <div
          class="absolute right-0 top-0 px-15 h-49 flex justify-center items-center"
        >
          <svg-icon
            name="icon-duihao"
            :size="16"
            color="#CCCCCC"
            class=""
            @click="confirm"
          />
        </div>
      </div>
      <div class="pt-5 pb-6">
        <NormalTabs
          class="px-15"
          :tabs="commonCategoryList"
          :active-id="commonCategoryId"
          :tab-class="tabClass"
          :disabled="loading"
          @update:active-id="commonCategoryId = $event"
        />
      </div>
      <div
        ref="scrollContainer"
        class="scroll-view scroll-view--vertical hide-scrollbar"
      >
        <div
          ref="scrollContent"
          class="pl-15 pb-5 min-h-375 max-h-375 text-13 text-white flex flex-row flex-wrap content-start overflow-y-auto"
        >
          <template v-if="noFailTimbreList.length">
            <div
              v-if="Number(commonCategoryId) === 0"
              class="mb-10 mr-10 w-76 h-76 relative rounded-10 bg-494950 flex flex-col items-center justify-center"
            >
              <svg-icon name="icon-tianjiayinse" :size="20" color="#FFFFFF" />
              <div class="mt-5">定制配音</div>
              <div
                class="absolute right-0 top-0 px-4 h-15 rounded-[0_10px_0_8px] flex items-center justify-center text-10 text-white"
                style="
                  background-image: linear-gradient(
                    116deg,
                    #6c3dff 0%,
                    #0f07ff 100%
                  );
                "
              >
                余{{
                  userAssetDetail.timbreBalance +
                  userAssetDetail.exTimbreBalance
                }}次
              </div>
            </div>
            <div
              v-for="item in noFailTimbreList"
              :key="item.timbreId"
              class="mb-10 mr-10 w-76 h-76 relative rounded-10 bg-494950 overflow-hidden flex flex-col items-center justify-center"
              :class="{
                'border-2 border-solid border-white font-bold':
                  selectTimbreId == item.timbreId
              }"
              @click="changeTimbreId(item.timbreId)"
              @touchstart="handleTouchStart($event, item)"
              @touchend="handleTouchEnd"
              @touchcancel="handleTouchEnd"
              @mousedown="handleMouseDown($event, item)"
              @mouseup="handleMouseEnd"
              @mouseleave="handleMouseEnd"
            >
              <div v-if="Number(commonCategoryId) === 0" class="text-center">
                {{ item.timbreAnchorName }}
              </div>
              <div v-if="Number(commonCategoryId) !== 0 && item.timbreName">
                <div class="text-center">
                  {{ item.timbreName.split("/")[0] }}
                </div>
                <div class="text-center mt-5">
                  {{ item.timbreName.split("/")[1] }}
                </div>
              </div>
              <svg-icon
                v-if="item.isCollect === 1"
                custom-class="absolute right-5 top-5 stars-class"
                name="icon-xing"
                :size="14"
                color="transparent"
              />
              <div
                v-if="item.timbreId === selectTimbreId"
                class="c-translucent-balck50 size-full absolute left-0 top-0 flex justify-center items-center"
              >
                <svg-icon name="icon-shezhi" :size="16" color="#fff" />
              </div>
              <div
                v-if="
                  item.timbreTaskStatus === 'COMMIT' ||
                  item.timbreTaskStatus === 'MAKING'
                "
                class="c-translucent-balck50 c-animation-opacity size-full absolute left-0 top-0 z-[2] flex flex-col justify-center items-center"
              >
                <div class="loading-circle border-4 h-20 w-20 rounded-[50%]" />
                <div class="mt-5 text-13 text-white">生成中</div>
              </div>
              <div
                v-if="item.timbreTaskStatus === 'FAIL'"
                class="px-5 h-15 absolute right-0 rounded-bl-6 top-0 z-[10] bg-FF4A35 text-white text-10 overflow-hidden flex justify-center items-center"
              >
                <div class="font-bold text-10">失败</div>
                <svg-icon name="icon-gengduo" :size="10" color="#fff" />
              </div>
              <div
                v-if="item.timbreVersionType === TIMBRE_VERSION_ENUM.SPEED"
                class="c-linear-purple px-6 leading-15 h-15 absolute right-0 bottom-0 rounded-tl-6 font-bold text-10"
              >
                极速
              </div>
              <div
                v-if="item.timbreVersionType === TIMBRE_VERSION_ENUM.EXCLUSIVE"
                class="c-linear-80FFBD px-6 leading-15 h-15 absolute right-0 bottom-0 rounded-tl-6 font-bold text-10 text-333333"
              >
                专属
              </div>
            </div>
          </template>
          <div class="size-full flex items-center justify-center">
            <div
              v-if="loading"
              class="w-8 h-8 border-t-2 border-blue-500 border-solid rounded-full animate-spin"
            />
            <EmptyState
              v-if="!loading && noFailTimbreList.length === 0"
              :text="'暂无数据'"
            />
          </div>
        </div>
      </div>
    </div>
  </van-popup>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import {
  CommonCategoryInfoData,
  getCommonCategoryList
} from "@/api/AiCopyGenerator";
import NormalTabs from "@/components/NormalTabs/index.vue";
import {
  collectTimbre,
  getTimbreInfoVoList,
  NoFailTimbreInfoData
} from "@/api/CreatePictureVideo";
import { UserAssetDetailData } from "@/api/MyHuman";
import { TIMBRE_VERSION_ENUM } from "@/enums";
import { showToast } from "vant";
defineOptions({
  name: "SelectTimbrePopup"
});
const props = defineProps({
  // 是否显示
  visible: {
    type: Boolean,
    required: true
  },
  // 我的音色列表
  myNoFailTimbreList: {
    type: Array as () => NoFailTimbreInfoData[],
    default: () => []
  },
  // 资产信息
  userAssetDetail: {
    type: Object as () => UserAssetDetailData,
    default: () => {}
  },
  // 选择的音色信息
  selectNoFailTimbreInfo: {
    type: Object as () => NoFailTimbreInfoData,
    default: () => {}
  },
  // 选择的音色ID
  selectNoFailTimbreCategoryId: {
    type: String,
    default: ""
  }
});

const emit = defineEmits(["update:visible", "confirm"]);

// 添加长按相关变量
const longPressTimer = ref<number | null>(null);
const longPressTimbreId = ref<string | null>(null);
// 长按事件处理
const handleLongPressStart = (e: Event, item: NoFailTimbreInfoData) => {
  // 清除可能存在的计时器
  handleLongPressEnd();

  // 设置新的计时器
  longPressTimer.value = setTimeout(() => {
    longPressTimbreId.value = item.timbreId;
    onLongPress(item);
    longPressTimer.value = null;
  }, 500) as unknown as number; // 500ms长按触发时间
};

const handleLongPressEnd = () => {
  if (longPressTimer.value) {
    clearTimeout(longPressTimer.value);
    longPressTimer.value = null;
  }
};

// 触摸事件处理
const handleTouchStart = (e: TouchEvent, item: NoFailTimbreInfoData) => {
  handleLongPressStart(e, item);
};

const handleTouchEnd = () => {
  handleLongPressEnd();
};

// 鼠标事件处理
const handleMouseDown = (e: MouseEvent, item: NoFailTimbreInfoData) => {
  handleLongPressStart(e, item);
};

const handleMouseEnd = () => {
  handleLongPressEnd();
};

// 长按回调函数
const onLongPress = (item: NoFailTimbreInfoData) => {
  if (Number(commonCategoryId.value) === 0) return;
  collectTimbrePort(item);
};

// 收藏
const collectTimbrePort = async (item: NoFailTimbreInfoData) => {
  const hasResult = await collectTimbre({ timbreId: item.timbreId });
  if (hasResult) {
    if (item.isCollect === 1) {
      showToast("已取消收藏");
    } else {
      showToast("收藏成功");
    }
    await getTimbreInfoVoListPort();
  }
};

// 修改点击事件处理，避免与长按冲突
const changeTimbreId = (timbreId: string) => {
  // 检查是否刚触发过长按
  if (longPressTimbreId.value === timbreId) {
    longPressTimbreId.value = null; // 重置长按标记
    return;
  }
  // 正常处理点击
  selectTimbreId.value = timbreId;
};

// 使用内部变量避免直接修改 prop
const innerVisible = ref(props.visible);

// 监听外部 show 变化
watch(
  () => props.visible,
  val => {
    innerVisible.value = val;
  }
);

// 监听内部变化并通知父组件
watch(innerVisible, val => {
  emit("update:visible", val);
});
// 选择
const confirm = () => {
  emit(
    "confirm",
    noFailTimbreList.value.find(item => item.timbreId === selectTimbreId.value),
    commonCategoryId.value
  );
  innerVisible.value = false;
};
// 音色列表
const noFailTimbreList = ref<NoFailTimbreInfoData[]>([]);
// 样式配置
const tabClass = ref({
  activeColor: "text-white",
  textColor: "text-999999",
  textSize: "text-15",
  activeTextSize: "text-16"
});
// 分类ID
const commonCategoryId = ref("1");
// 分类列表
const commonCategoryList = ref<CommonCategoryInfoData[]>([]);
// 分类请求接口
const getCommonCategoryListPort = async () => {
  const commonCategoryResult = await getCommonCategoryList({ categoryType: 2 });
  // 添加收藏
  commonCategoryResult.unshift({
    categoryId: "1",
    remark: "",
    sort: 0,
    type: 0,
    name: "收藏"
  });
  // 添加我的
  commonCategoryResult.unshift({
    categoryId: "0",
    remark: "",
    sort: 0,
    type: 0,
    name: "我的"
  });
  commonCategoryList.value = commonCategoryResult.map(item => ({
    ...item,
    id: item.categoryId
  }));
  selectTimbreId.value = props.selectNoFailTimbreInfo.timbreId;
  commonCategoryId.value = props.selectNoFailTimbreCategoryId;
};
// 选择音色
const selectTimbreId = ref("");

// 添加加载状态
const loading = ref(false);
// 获取音色列表
watch(
  () => commonCategoryId.value,
  val => {
    if (val) {
      noFailTimbreList.value = [];
      if (val === "0") {
        noFailTimbreList.value = props.myNoFailTimbreList;
      } else {
        getTimbreInfoVoListPort();
      }
    }
  }
);
// 分类请求接口
const getTimbreInfoVoListPort = async () => {
  loading.value = true;
  try {
    const timbreInfoVoListData = await getTimbreInfoVoList({
      categoryId: commonCategoryId.value,
      getCollect: commonCategoryId.value === "1" ? 1 : 0,
      pageNo: 1,
      pageSize: 9999
    });
    noFailTimbreList.value = timbreInfoVoListData.records;
  } finally {
    loading.value = false;
  }
};
onMounted(() => {
  getCommonCategoryListPort();
  noFailTimbreList.value = props.myNoFailTimbreList;
});
</script>

<style scoped lang="less">
.stars-class {
  background: linear-gradient(116deg, #ffe585 19%, #ffc94c 100%);
  background-clip: text;
  color: transparent;
}
</style>
